#!/bin/bash


# chmod +x deploy.sh


# 定义颜色
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 打印带颜色的消息
log_info() {
    echo -e "${GREEN}[INFO] $1${NC}"
}

log_warn() {
    echo -e "${YELLOW}[WARN] $1${NC}"
}

log_error() {
    echo -e "${RED}[ERROR] $1${NC}"
}

# 等待 Pod 就绪
wait_for_pod() {
    local label="$1"
    local timeout="$2"
    local start_time=$(date +%s)
    local pod_name=""
    
    log_info "等待 $label Pod 就绪..."
    
    while true; do
        # 获取 Pod 名称
        pod_name=$(sudo k3s kubectl get pod -l app=$label -o jsonpath="{.items[0].metadata.name}" 2>/dev/null)
        
        # 检查 Pod 是否就绪
        if [ ! -z "$pod_name" ]; then
            ready_status=$(sudo k3s kubectl get pod $pod_name -o jsonpath="{.status.containerStatuses[0].ready}" 2>/dev/null)
            if [ "$ready_status" == "true" ]; then
                log_info "$label Pod 已就绪"
                return 0
            fi
        fi
        
        # 检查超时
        current_time=$(date +%s)
        elapsed_time=$((current_time - start_time))
        if [ $elapsed_time -gt $timeout ]; then
            log_error "$label Pod 等待超时"
            return 1
        fi
        
        sleep 2
    done
}

# 检查必要的命令是否存在
check_requirements() {
    log_info "检查环境要求..."
    
    if ! command -v docker &> /dev/null; then
        log_error "未找到 docker 命令，请先安装 Docker"
        exit 1
    fi

    if ! command -v k3s &> /dev/null; then
        log_error "未找到 k3s 命令，请先安装 K3s"
        exit 1
    fi
}

# 构建 Flask 应用镜像
build_flask_image() {
    log_info "构建 Flask 应用镜像..."
    cd app && \
    sudo docker build -t flask-app:latest . && \
    cd .. && \
    sudo docker save flask-app:latest -o flask-app.tar && \
    sudo k3s ctr images import flask-app.tar
    
    if [ $? -ne 0 ]; then
        log_error "构建 Flask 镜像失败"
        exit 1
    fi
}

# 创建必要的目录
create_directories() {
    log_info "创建日志目录..."
    mkdir -p logs/{mysql,flask,nginx}
}

# 部署应用
deploy_application() {
    log_info "开始部署应用..."
    
    # 部署 MySQL
    log_info "部署 MySQL..."
    sudo k3s kubectl apply -f k8s/mysql-init.yaml -f k8s/mysql-deployment.yaml
    
    # 等待 MySQL 就绪
    wait_for_pod "mysql" 120 || exit 1
    
    # 等待 MySQL 服务完全启动
    log_info "等待 MySQL 服务初始化..."
    sleep 20
    
    # 部署 Flask 应用
    log_info "部署 Flask 应用..."
    sudo k3s kubectl apply -f k8s/flask-deployment.yaml
    
    # 等待 Flask 就绪
    wait_for_pod "flask-app" 60 || exit 1
    
    # 部署 Nginx
    log_info "部署 Nginx..."
    sudo k3s kubectl apply -f k8s/nginx-deployment.yaml
    
    # 等待 Nginx 就绪
    wait_for_pod "nginx" 60 || exit 1
}

# 检查部署状态
check_deployment() {
    log_info "检查部署状态..."
    
    # 获取 Pod 状态
    log_info "当前 Pod 状态："
    sudo k3s kubectl get pods
    
    # 验证数据库初始化
    log_info "验证数据库初始化..."
    mysql_pod=$(sudo k3s kubectl get pod -l app=mysql -o jsonpath="{.items[0].metadata.name}")
    
    # 尝试多次连接数据库
    max_retries=5
    retry_count=0
    while [ $retry_count -lt $max_retries ]; do
        if sudo k3s kubectl exec -it $mysql_pod -- mysql -uuser -ppassword -e "USE testdb; SHOW TABLES; SELECT * FROM items;" 2>/dev/null; then
            log_info "数据库连接成功"
            break
        else
            retry_count=$((retry_count + 1))
            if [ $retry_count -eq $max_retries ]; then
                log_error "无法连接到数据库"
                return 1
            fi
            log_warn "数据库连接失败，重试中... ($retry_count/$max_retries)"
            sleep 5
        fi
    done
    
    # 测试 API 访问
    log_info "测试 API 访问..."
    response=$(curl -s http://localhost:30080/items)
    if [ $? -eq 0 ] && [ ! -z "$response" ]; then
        log_info "API 访问成功"
        echo $response
    else
        log_error "API 访问失败"
        return 1
    fi
}

# 清理部署
cleanup() {
    log_warn "清理所有部署..."
    sudo k3s kubectl delete -f k8s/
    rm -f flask-app.tar
}

# 显示使用帮助
show_help() {
    echo "使用方法: $0 [命令]"
    echo "命令:"
    echo "  start    - 启动应用"
    echo "  restart  - 重启应用"
    echo "  stop     - 停止应用"
    echo "  status   - 查看应用状态"
    echo "  cleanup  - 清理所有资源"
    echo "  help     - 显示此帮助信息"
}

# 主函数
main() {
    case "$1" in
        "start")
            check_requirements
            create_directories
            build_flask_image
            deploy_application
            check_deployment
            log_info "应用已启动完成！"
            log_info "访问地址: http://localhost:30080"
            ;;
            
        "restart")
            log_info "重启应用..."
            cleanup
            sleep 5
            create_directories
            build_flask_image
            deploy_application
            check_deployment
            log_info "应用已重启完成！"
            log_info "访问地址: http://localhost:30080"
            ;;
            
        "stop")
            log_info "停止应用..."
            cleanup
            log_info "应用已停止！"
            ;;
            
        "status")
            log_info "应用状态："
            sudo k3s kubectl get pods
            ;;
            
        "cleanup")
            cleanup
            log_info "清理完成！"
            ;;
            
        "help"|"")
            show_help
            ;;
            
        *)
            log_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 